import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:open_document/my_files/init.dart';
import 'package:photo_view/photo_view.dart';

import 'enum/constants.dart';

class DocumentViewer extends StatefulWidget {
  final String filePath;

  const DocumentViewer({Key? key, required this.filePath}) : super(key: key);

  @override
  State<DocumentViewer> createState() => _DocumentViewerState();
}

class _DocumentViewerState extends State<DocumentViewer> {
  int columns = 0;
  int rows = 0;
  String filePath = "";
  String docExtension = "";

  getDocExtension() {
    if (widget.filePath != "") {
      return widget.filePath.substring(widget.filePath.lastIndexOf('.')); //To get the file extension
    }
  }

  @override
  void initState() {
    docExtension = getDocExtension();
    if (docExtension == Constants.txt) {
      readFromTxtFile();
      // } else if ([
      //   Constants.docx, /*Constants.doc*/
      // ].contains(docExtension)) {
      //   readFromDocxFile();
    }
    super.initState();
  }

  String content = "";

  Future<String> readFromTxtFile() async {
    try {
      final file = File(widget.filePath);
      content = await file.readAsString();
      setState(() {});
      return content;
    } catch (e) {
      return "$e";
    }
  }

  // Future<String> readFromDocxFile() async {
  //   final file = File(widget.filePath);
  //   final bytes = await file.readAsBytes();
  //   content = docxToText(bytes);
  //   setState(() {});
  //   return content; // docx to text
  // }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      width: MediaQuery.sizeOf(context).width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (docExtension == Constants.pdf) ...[
            Expanded(
                child: PDFView(
              filePath: widget.filePath,
              enableSwipe: true,
              autoSpacing: false,
              pageFling: false,
            )), //To open the pdf
          ] else if ([/*Constants.docx,*/ /*Constants.doc,*/ Constants.txt].contains(docExtension)) ...[
            Expanded(child: SingleChildScrollView(child: Container(padding: const EdgeInsets.all(20.0), color: Colors.white, child: Text(content)))), //To open docx and doc files
          ] else if ([Constants.jpeg, Constants.jpg, Constants.png].contains(docExtension)) ...[
            Expanded(
              child: PhotoView(
                imageProvider: FileImage(File(widget.filePath)),
                // To view image such as jpg,jpeg,png
                minScale: PhotoViewComputedScale.contained * 0.8,
                maxScale: PhotoViewComputedScale.covered * 1,
                initialScale: PhotoViewComputedScale.contained,
                basePosition: Alignment.topCenter,
                backgroundDecoration: const BoxDecoration(color: Colors.white),
              ),
            ),
          ] /*else if (docExtension == Constants.xlsx)
            Builder(builder: (context) {
              Excel excel = Excel.decodeBytes(File(widget.filePath).readAsBytesSync());
              var output = "";
              for (var table in excel.tables.keys) {
                output += '$table\n'; // t Name
                output += 'col : ${excel.tables[table]?.maxCols}\n'; // t Name
                output += 'row : ${excel.tables[table]?.maxRows}\n'; // t Name
                for (List<Data?> row in excel.tables[table]?.rows ?? []) {
                  String rowStr = "";
                  for (Data? data in row) {
                    rowStr += '${data?.value ?? 'cell'} ';
                  }
                  // logWTF(rowStr);
                  output += '$rowStr\n';
                }
              }
              return Expanded(child: Text(output));
            })*/
          else
            Builder(builder: (context) {
              // Navigator.of(context).maybePop();
              OpenDocument.openDocument(filePath: widget.filePath);
              return Expanded(child: Container(margin: const EdgeInsets.only(top: 150), alignment: Alignment.topCenter, child: const SizedBox(child: Text('请选择应用打开文件'))));
            })
        ],
      ),
    );
  }
}
